package mk.jug.academy.service;

import javax.persistence.NoResultException;

import mk.jug.academy.dao.SponsorDAO;
import mk.jug.academy.exception.BusinessException;
import mk.jug.academy.model.Page;
import mk.jug.academy.model.Sponsor;
import mk.jug.academy.model.SponsorStatus;
import mk.jug.academy.preconditions.ErrorCodes;
import mk.jug.academy.preconditions.PreconditionExceptions;
import mk.jug.academy.util.Utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;


/**
 * Contains business logic implementation for the {@link SponsorService}.
 *
 * @author Ice.Penov
 */
@Service
public class SponsorServiceImpl implements SponsorService {

	@Autowired private SponsorDAO sponsorDAO;
	
	@Override
	public void register(Sponsor sponsor) {
		Assert.notNull(sponsor.getName(), PreconditionExceptions.MISSING_NAME);
		Assert.notNull(sponsor.getName(), PreconditionExceptions.MISSING_EMAIL);
		sponsor.setStatus(SponsorStatus.REGISTERED);
		if (!exists(sponsor.getEmail())) {			
			sponsorDAO.save(sponsor);
		} else {
			throw new BusinessException(ErrorCodes.ERROR_EMAIL_EXISTS);
		}
	}

	@Override
	public Page<Sponsor> listRegistered(int pageNumber, int itemsPerPage) {
		return sponsorDAO.findByStatus(SponsorStatus.REGISTERED, Utils.calculateStart(pageNumber, itemsPerPage), itemsPerPage);
	}
	
	@Override
	public Page<Sponsor> listActive(int pageNumber, int itemsPerPage) {
		return sponsorDAO.findByStatus(SponsorStatus.ACTIVE, Utils.calculateStart(pageNumber, itemsPerPage), itemsPerPage);
	}

	@Override
	public Page<Sponsor> listDeleted(int pageNumber, int itemsPerPage) {
		return sponsorDAO.findByStatus(SponsorStatus.DELETED, Utils.calculateStart(pageNumber, itemsPerPage), itemsPerPage);
	}

	@Override
	public void activate(Sponsor sponsor) {
		sponsor.setStatus(SponsorStatus.ACTIVE);
		sponsorDAO.save(sponsor);
	}

	@Override
	public void delete(Sponsor sponsor) {
		sponsor.setStatus(SponsorStatus.DELETED);
		sponsorDAO.save(sponsor);
	}
	
	@Override
	public Sponsor findByEmail(String email) {
		Sponsor s = null;
		try {
			s = sponsorDAO.findActiveByEmail(email);
		} catch (NoResultException e) {
			;
		}
		return s;
	}
	
	@Override
	public boolean exists(String email) {
		try {
			sponsorDAO.findAnyByEmail(email);
		} catch (NoResultException e) {
			return false;
		}
		return true;
	}

	@Override
	public Sponsor load(Long id) {
		return sponsorDAO.find(Sponsor.class, id);
	}
	
}